﻿#include "mclient.h"

#include <QTcpSocket>
#include <QHostAddress>
#include <QAbstractSocket>

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>

#include <QDebug>

class MClientPrivate
{
public:
    MClientPrivate() {}
public:
    QTcpSocket *socket;
    QString ipAddr;
    int port;
};

MClient::MClient(const QString &ipAddr, int port, QObject *parent) 
    : QObject(parent)
{
    qWarning()<<"------MClient::MClien-------";
    
    d = new MClientPrivate();
    d->ipAddr = ipAddr;
    d->port = port;
    
    d->socket = new QTcpSocket(this);
    connect(d->socket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(d->socket,SIGNAL(readyRead()),this,SLOT(socketReadyRead()));
}

MClient::~MClient()
{
    d->socket->close();
    delete d;
}

void MClient::sendData(const QString &data)
{
    if( d->socket->state() == QAbstractSocket::ConnectedState ){
        //qWarning()<<"send =data="<<data;
        d->socket->write(data.toUtf8());
    }
    else{
        qWarning()<<" not create connectioned.";
    }
}

void MClient::startConnect()
{ 
    d->socket->connectToHost(QHostAddress(d->ipAddr), d->port);
    if( d->socket->waitForConnected() )
    {
        
    }   
}

void MClient::socketStateChanged(QAbstractSocket::SocketState state)
{
    //emit stateChanged(state);
}

void MClient::socketReadyRead()
{
    QJsonObject jsObj = getRootJsObj(d->socket->readAll());
    if( jsObj.value("cmd").toString() == "refresh" )
        emit newRefresh(jsObj);
    else
        emit newCommand(jsObj);
} 

QJsonObject MClient::getRootJsObj(const QByteArray &data)
{
    QJsonParseError jsError;
    QJsonDocument jsDoc = QJsonDocument::fromJson(data, &jsError);
    
    if(jsError.error != QJsonParseError::NoError )
        return QJsonObject();
    
    if(jsDoc.isNull() || jsDoc.isEmpty())
        return QJsonObject();
    
    if( jsDoc.isObject() )
        return jsDoc.object();
    return QJsonObject();
} 
